package com.zsj.hello.four;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zsj.hello.util.RabbimqFactoryUtil;
import com.zsj.hello.util.SleepUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author https://gitee.com/zhengshengjun
 * @date 2023/8/30.
 */
public class Work01 {
    public static final String ACK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbimqFactoryUtil.getRabbitMQChannel();
        System.out.println("Work01等待接收消息中~~~~~ 时间较短");

        //预取值
//        int prefetchCount =1;

        int prefetchCount = 5;

        //设置未不公平分发
        channel.basicQos(prefetchCount);


        DeliverCallback deliverCallback = (t, m) -> {
            try {
                SleepUtil.sleep(1);
                System.out.println("Work01接收信息为：" + new String(m.getBody(), StandardCharsets.UTF_8));
                //应答
                /**
                 * 1、消息的标记tag
                 * 2、是否批量处理应答
                 */
                channel.basicAck(m.getEnvelope().getDeliveryTag(), false);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };

        CancelCallback cancelCallback = (t) -> {
            System.out.println("消息被取消");
        };

        //手动应答
        boolean autoAck = false;
        channel.basicConsume(ACK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);

    }
}
